<?php

include ("class/Tim.php");
include ("class/Round.php");
include ("class/Match.php");
include ("class/Connection.php");
include ("components/functions.php");
include ("components/connection.php");

function scheduler($teams){
	$n = count($teams);
    if (count($teams)%2 != 0){
		$tim = new Tim(0);
		$tim->ime = "BYE";
        array_push($teams, $tim);
    }
    $away = array_splice($teams,(count($teams)/2));
    $home = $teams;
    for ($i=0; $i < count($home)+count($away)-1; $i++){
        for ($j=0; $j<count($home); $j++){
            if (($i%2 !=0) && ($j%2 ==0)){
                $schedule[$i][$j]["Home"]=$away[$j];
                $schedule[$i][$j]["Away"]=$home[$j];
            } else {
                $schedule[$i][$j]["Home"]=$home[$j];
                $schedule[$i][$j]["Away"]=$away[$j]; 
            }
        }
        if(count($home)+count($away)-1 > 2){
            array_unshift($away,array_shift(array_splice($home,1,1)));
            array_push($home,array_pop($away));
        }
    }
	

    return $schedule;
}

?>

<?php $members = getAllTeams(); shuffle($members); ?> 
<?php $schedule = scheduler($members); ?> 
<?php

foreach($schedule AS $round => $games){
	$runda = new Round(0);
	$runda->liga = 1;
	$runda->datum = date("Y-m-d", strtotime("16 FEB 2013 + ".$round." WEEK"));
    echo "Round: ".($round+1)."<BR>";
    foreach($games AS $play){
		$m = new Match();
		$m->domacin = $play["Home"];
		$m->gost = $play["Away"];
		$m->liga = 1;
		$m->kolo = $round+1;
		$m->odigrana = 0;
		$runda->mecevi[] = $m;
    }
	shuffle($runda->mecevi);
	$i = 0;
	foreach($runda->mecevi as $mec) {
		$mec->vreme = date("H:i:s", strtotime("12:00 + ". $i++ ." HOURS"));
		echo $mec->vreme,": ", $mec->domacin->ime, " - ", $mec->gost->ime, "<br />";
	}
    echo "<BR />";
	$runda->insertIntoDb();
}
?> 